package com.jiadeyu.service.impl;

import com.jiadeyu.mapper.UserMapper;
import com.jiadeyu.pojo.User;
import com.jiadeyu.service.UserService;
import com.jiadeyu.utils.Md5Util;
import com.jiadeyu.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public void register(String username, String password) {
        String md5String = Md5Util.encrypByMd5(password);
        userMapper.add(username, md5String);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(String.valueOf(LocalDateTime.now()));
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get("Authorization");
        Integer userId = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, userId);
    }

    @Override
    public void updatePassword(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get("Authorization");
        Integer userId = (Integer) map.get("id");
        userMapper.updatePassword(newPwd, userId);
    }
}
